//
//  Process.c
//  OperatingSystem
//
//  Created by Jay Fernandez on 3/14/12.
//  Copyright (c) 2012 University of Washington Tacoma. All rights reserved.
//

#include <stdlib.h>
#include <stdio.h>
#include "Process.h"

int next_pid = 0;   //next available pid

/*
 * Constructor for a process.
 */
ProcessStr* createProcess(enum interrupt syscall) {
    ProcessStr *process = (ProcessStr*) malloc(sizeof(*process));
    int i;
    if (process == NULL) {
        fprintf(stderr, "createProcess() : malloc error");
        return NULL;
    }
    process->type = syscall;
    process->num_steps = rand() % 1000 + 10;
    process->num_requests = rand() % 10;
    process->requests = malloc( sizeof process->num_requests );
    process->priority = random() % 4;
    for (i = 0; i <process->num_requests; i++) {
    	process->requests[i] = createRequest(process);
    }
    array_list_init(process->tickets, 100);
    return process;
}

/*
 * Constructor for a Process Control Block.
 */
PCBStr* createPCB(ProcessStr *process) {
    PCBStr *pcb = (PCBStr*) malloc(sizeof(*pcb));
    if (pcb == NULL) {
        fprintf(stderr, "createPCB() : malloc error");
        return NULL;
    }
    pcb->pid = next_pid;
    next_pid++;
    pcb->next_step = 1;
    pcb->state = READY;
    pcb->waiting_on = -1;
    pcb->owns = -1;
    pcb->process = process;
    return pcb;
}

/*
 * Constructor for a request.
 */
RequestStr* createRequest(ProcessStr *process) {
    RequestStr *request = (RequestStr*) malloc(sizeof(*request));
    if (request == NULL) {
        fprintf(stderr, "createRequest() : malloc error");
        return NULL;
    }
    request->step = rand() % process->num_steps;
    return request;
}
